package com.ys.service.purchase.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.business.TpProductActiveComponent;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.purchase.*;
import com.ys.entity.storage.TccOfflineAssemble;
import com.ys.entity.storage.TccOfflineAssembleItem;
import com.ys.entity.sys.TsUserChange;
import com.ys.enume.purchase.TcgOfflinePurchaseInStorageEnum;
import com.ys.enume.storage.TccOfflineAssembleEnum;
import com.ys.enume.storage.TccStockFrozenRunningEnum;
import com.ys.enume.storage.TccStockSourceEnum;
import com.ys.mapper.purchase.TcgOfflinePurchaseInStorageMapper;
import com.ys.mapper.purchase.TcgPurchaseByOrderMapper;
import com.ys.mapper.purchase.TcgPurchaseByPlanSonMapper;
import com.ys.mapper.purchase.TcgPurchasePlanGoodsMapper;
import com.ys.mapper.storage.TccOfflineAssembleItemMapper;
import com.ys.mapper.storage.TccOfflineAssembleMapper;
import com.ys.service.purchase.TcgOfflinePurchaseInStorageService;
import com.ys.service.storage.TccStockControlService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: fxz
 * @CreateTime: 2024-11-14
 * @Description: 线上入库单
 * @Version: 1.0
 */
@Service("tcgOfflinePurchaseInStorageService")
public class TcgOfflinePurchaseInStorageServiceImpl implements TcgOfflinePurchaseInStorageService {

    private static final Logger logger = LoggerFactory.getLogger(TcgOfflinePurchaseInStorageServiceImpl.class);

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private TcgOfflinePurchaseInStorageMapper tcgOfflinePurchaseInStorageMapper;

    @Autowired
    private CommonApiService<TcgOfflinePurchaseInStorage> commonApiService;

    private final Long MENUID = MenuId.TCG_OfflinePurchaseInStorage;

    private final Long MENUID1 = MenuId.TCC_OfflineAssemble;

    @Autowired
    private TccStockControlService tccStockControlService;

    @Autowired
    private TcgPurchaseByPlanSonMapper tcgPurchasePlanSonMapper;

    @Autowired
    private TcgPurchasePlanGoodsMapper tcgPurchasePlanGoodsMapper;

    @Autowired
    private CommonApiService<TccOfflineAssemble> commonApiServiceAssemble;

    @Autowired
    private TccOfflineAssembleMapper tccOfflineAssembleMapper;

    @Autowired
    private TccOfflineAssembleItemMapper tccOfflineAssembleItemMapper;

    @Autowired
    private TcgPurchaseByOrderMapper tcgPurchaseByOrderMapper;

    @Autowired
    private PdfService pdfService;

    /**
     * 物流修改
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R wlUpdate(Map<String, Object> params) throws Exception {
        if(checkUtil.isNullByObject(params.get("choooseDatas"))){
            return R.error("请选择要操作的信息");
        }
        if(checkUtil.isNullByObject(params.get("aliLogisticsBillNo"))){
            return R.error("物流运单号不允许为空!");
        }
        if(checkUtil.isNullByObject(params.get("aliLogisticsPlace"))){
            return R.error("物流渠道不允许为空!");
        }
        JSONArray tcgPurchaseOrderWcs = JSON.parseArray(params.get("choooseDatas").toString());

        HashSet<Long> listPurchaseOrderId = new HashSet<Long>();
        for (int i = 0; i < tcgPurchaseOrderWcs.size(); i++) {
            JSONObject jsonObject = tcgPurchaseOrderWcs.getJSONObject(i);
            if(jsonObject.get("purchaseOrderId")!=null){
                Long id = Long.valueOf(jsonObject.get("purchaseOrderId").toString());
                listPurchaseOrderId.add(id);
            }else {
                return R.error("选择的数据中存在未创建订单,不允许物流信息修改!");
            }
        }

        for (Long id : listPurchaseOrderId){
            List<TcgPurchaseByOrderSon> tcgPurchaseByOrderSons = new TcgPurchaseByOrderSon().setPid(id).queryList();
            for (TcgPurchaseByOrderSon tcgPurchaseByOrderSon : tcgPurchaseByOrderSons){
                int count = new TcgOfflinePurchaseInStorage().
                        setPurchaseOrderSonId(tcgPurchaseByOrderSon.getId()).setStorageStatus(TcgOfflinePurchaseInStorageEnum.StorageStatus.IN_STORAGE.value).count();
                if (count != 0){
                    return R.error("选择的数据已入库,不允许物流信息修改!");
                }
            }
        }

        for (Long id : listPurchaseOrderId){
            List<TcgPurchaseByOrderSon> tcgPurchaseByOrderSons = new TcgPurchaseByOrderSon().setPid(id).queryList();
            for (TcgPurchaseByOrderSon tcgPurchaseByOrderSon : tcgPurchaseByOrderSons) {
                TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage = new TcgOfflinePurchaseInStorage()
                        .setPurchaseOrderSonId(tcgPurchaseByOrderSon.getId())
                        .setStorageStatus(TcgOfflinePurchaseInStorageEnum.StorageStatus.STOCK_PENDING.value)
                        .queryFirst();
                TcgPurchaseByOrder tcgPurchaseOrder = new TcgPurchaseByOrder().setId(id).queryFirst();
                tcgPurchaseOrder.setAliLogisticsBillNo(params.get("aliLogisticsBillNo").toString());
                tcgPurchaseOrder.setAliLogisticsPlace(params.get("aliLogisticsPlace").toString());
                tcgPurchaseByOrderMapper.update(tcgPurchaseOrder);
                //有入库单修改入库单相应信息|无入库单促发入库单相应信息
                if (tcgOfflinePurchaseInStorage != null) {
                    tcgOfflinePurchaseInStorage.setAliLogisticsBillNo(params.get("aliLogisticsBillNo").toString());
                    tcgOfflinePurchaseInStorage.setAliLogisticsPlace(params.get("aliLogisticsPlace").toString());
                    tcgOfflinePurchaseInStorageMapper.update(tcgOfflinePurchaseInStorage);
                } else {
                    R add = addTcgOfflinePurchaseInStorage(tcgPurchaseOrder, tcgPurchaseByOrderSon.getId(), params.get("aliLogisticsBillNo").toString(),
                            params.get("aliLogisticsPlace").toString(), 0
                            , TcgOfflinePurchaseInStorageEnum.AssembledStatus.NOT_ASSEMBLY.value, null);
                    if (add.getCode() != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(add.getMsg());
                    }
                }
            }
        }
        return R.ok("物流信息修改成功!");
    }

    /**
     * 新增线上采购入库单
     * @param tcgPurchaseOrder 采购订单
     * @param tcgPurchaseOrderSonId  采购订单子件id
     * @param aliLogisticsBillNo 物流运单号
     * @param aliLogisticsPlace 物流渠道
     * @param documentSource 0.正常入库|1.组装报错
     * @param assembledStatus 0.未入组装 | 1.已入组装 | 2.组装报错
     * @param subStorageNum 未入库数量（来源当正常入库,订单入库数量，则组装报错,缺失数量）
     * @return
     * @throws Exception
     */
    @Override
    public R addTcgOfflinePurchaseInStorage(TcgPurchaseByOrder tcgPurchaseOrder,Long tcgPurchaseOrderSonId
            ,String aliLogisticsBillNo,String aliLogisticsPlace,Integer documentSource,Integer assembledStatus
            ,Integer subStorageNum) throws Exception {
        TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorageNew = new TcgOfflinePurchaseInStorage();

        try {
            //查询订单子件信息
            TcgPurchaseByOrderSon tcgPurchaseOrderSon = new TcgPurchaseByOrderSon().setId(tcgPurchaseOrderSonId).queryFirst();
            if (tcgPurchaseOrderSon == null){
                return R.error("物流运单号不允许为空!");
            }
            //查询lisitng数据
            Map<String, Object> tpProductActiveMap = new TpProductActiveComponent()
                    .addLeftJoin("TP_ProductActive B ON A.Pcode = B.code")
                    .addField("B.code productCode,B.name productName,B.img,B.img1,B.img2")
                    .setCode(tcgPurchaseOrderSon.getSubCode())
                    .queryFirstMap();
            //查询采购计划子件数据
            TcgPurchaseByPlanSon tcgPurchasePlanSon = new TcgPurchaseByPlanSon().setId(tcgPurchaseOrderSon.getPurchasePlanSonId()).queryFirst();

            //查询采购计划母件数据
            TcgPurchasePlanGoods tcgPurchasePlanGoods = new TcgPurchasePlanGoods().setId(tcgPurchasePlanSon.getPid()).queryFirst();

            //第一步查询计划单有几个订单
            //第二步查询之前入库了几次
            if (documentSource == 0){
                subStorageNum = tcgPurchasePlanSon.getSubTotalAmount();
            }
            String bid = commonApiService.getCommonNextBid(MENUID);
            tcgOfflinePurchaseInStorageNew.setBid(bid);
            tcgOfflinePurchaseInStorageNew.setAliLogisticsBillNo(aliLogisticsBillNo);
            tcgOfflinePurchaseInStorageNew.setAliLogisticsPlace(aliLogisticsPlace);
            tcgOfflinePurchaseInStorageNew.setProductCode(tpProductActiveMap.get("productCode").toString());
            tcgOfflinePurchaseInStorageNew.setProductName(tpProductActiveMap.get("productName").toString());
            tcgOfflinePurchaseInStorageNew.setSubCode(tpProductActiveMap.get("code").toString());
            tcgOfflinePurchaseInStorageNew.setSubName(tpProductActiveMap.get("name").toString());
            tcgOfflinePurchaseInStorageNew.setProductImgOne(tpProductActiveMap.get("img") == null ? null : tpProductActiveMap.get("img").toString());
            tcgOfflinePurchaseInStorageNew.setProductImgTwo(tpProductActiveMap.get("img1") == null ? null : tpProductActiveMap.get("img1").toString());
            tcgOfflinePurchaseInStorageNew.setProductImgThree(tpProductActiveMap.get("img2") == null ? null : tpProductActiveMap.get("img2").toString());
            tcgOfflinePurchaseInStorageNew.setVgsbm(tcgPurchaseOrder.getVgsbm());
            tcgOfflinePurchaseInStorageNew.setSpNumber(tcgPurchasePlanGoods.getSpAmount());
            tcgOfflinePurchaseInStorageNew.setSubBomNumber(tcgPurchasePlanSon.getSubAmount());
            tcgOfflinePurchaseInStorageNew.setSubPurchasePrice(tcgPurchaseOrderSon.getSubRealityPrice());
            tcgOfflinePurchaseInStorageNew.setSubStorageNum(subStorageNum);
            //子件加购
            tcgOfflinePurchaseInStorageNew.setJgSl(tcgPurchasePlanSon.getJgSl());
            tcgOfflinePurchaseInStorageNew.setPurchaseOrderSonId(tcgPurchaseOrderSonId);
            tcgOfflinePurchaseInStorageNew.setPurchaseOrderGoodsId(tcgPurchasePlanGoods.getId());
            tcgOfflinePurchaseInStorageNew.setStorageStatus(TcgOfflinePurchaseInStorageEnum.StorageStatus.STOCK_PENDING.value);
            tcgOfflinePurchaseInStorageNew.setAssembledStatus(assembledStatus);
            tcgOfflinePurchaseInStorageNew.setPrintStatus(TcgOfflinePurchaseInStorageEnum.PrintStatus.NOT_PRINT.value);
            tcgOfflinePurchaseInStorageNew.setStatus(1);
            tcgOfflinePurchaseInStorageNew.setDocumentSource(documentSource);
            //母件数量为0，只有加购数量
            if (tcgPurchasePlanGoods.getSpAmount() == null  || tcgPurchasePlanGoods.getSpAmount() == 0){
                tcgOfflinePurchaseInStorageNew.setGenerateStatus(1);
            }
            tcgOfflinePurchaseInStorageMapper.insert(tcgOfflinePurchaseInStorageNew);
        }catch (Exception e){
            logger.error("新增线上采购入库失败：失败原因如下" + e.getMessage());
            return R.error("新增线上采购入库失败!");
        }

        return R.ok("操作成功",tcgOfflinePurchaseInStorageNew.getBid());
    }


    /**
     * 取消入库
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R cancelStorage(Map<String, Object> params) throws Exception {
        if(checkUtil.isNullByObject(params.get("choooseDatas"))){
            return R.error("请选择要操作的信息");
        }

        JSONArray tcgOfflinePurchaseInStorageS = JSON.parseArray(params.get("choooseDatas").toString());

        for (int i = 0; i < tcgOfflinePurchaseInStorageS.size(); i++) {
            JSONObject jsonObject = tcgOfflinePurchaseInStorageS.getJSONObject(i);
            Long id = Long.valueOf(jsonObject.get("id").toString());
            TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage = new TcgOfflinePurchaseInStorage().
                    setId(id).queryFirst();
            if (tcgOfflinePurchaseInStorage.getAssembledStatus() == TcgOfflinePurchaseInStorageEnum.AssembledStatus.ASSEMBLY_ERROR.value){
                return R.error("选择的数据是组装报错,不允许取消入库!");
            }
            if (tcgOfflinePurchaseInStorage.getStorageStatus() == TcgOfflinePurchaseInStorageEnum.StorageStatus.IN_STORAGE.value){
                return R.error("选择的数据已入库,不允许取消入库!");
            }
            if (tcgOfflinePurchaseInStorage.getStorageStatus() == TcgOfflinePurchaseInStorageEnum.StorageStatus.CANCEL_STORAGE.value){
                return R.error("选择的数据已取消入库,不允许取消入库!");
            }
        }

        for (int i = 0; i < tcgOfflinePurchaseInStorageS.size(); i++) {
            JSONObject jsonObject = tcgOfflinePurchaseInStorageS.getJSONObject(i);
            Long id = Long.valueOf(jsonObject.get("id").toString());
            TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage = new TcgOfflinePurchaseInStorage()
                    .setId(id)
                    .setStorageStatus(TcgOfflinePurchaseInStorageEnum.StorageStatus.CANCEL_STORAGE.value)
                    ;
            tcgOfflinePurchaseInStorageMapper.update(tcgOfflinePurchaseInStorage);
        }
        return R.ok("取消入库成功!");
    }

    /**
     * 采购入库
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R updateRk(Map<String, Object> params) throws Exception{
        try {
            if (params.get("listId") == null) {
                return R.error("采购入库数据未选择!");
            }
            if (params.get("chw") == null) {
                return R.error("货位数据未选择!");
            }

            String listId = params.get("listId").toString();
            String[] split = (listId.substring(1, listId.length() - 1)).split(",");

            HashSet<String> listPurchaseOrderId = new HashSet<String>();
            for(String purchaseOrderId : split) {
                listPurchaseOrderId.add(purchaseOrderId);
            }
            for (String purchaseOrderId :listPurchaseOrderId){
                List<TcgOfflinePurchaseInStorage> tcgOfflinePurchaseInStorageList = new TcgOfflinePurchaseInStorage()
                        .addLeftJoin("TCG_PurchaseByOrderSon C ON C.id = A.PurchaseOrderSonId")
                        .addLeftJoin("TCG_PurchaseByOrder AA ON C.Pid = AA.id")
                        .where("AA.id = '" + purchaseOrderId + "'")
                        .setStorageStatus(0)
                        .queryList();
                if (tcgOfflinePurchaseInStorageList.size() == 0){
                    return R.error("选择的数据无待入库数据,不允许采购入库!");
                }
                for (TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage : tcgOfflinePurchaseInStorageList){
                    if (tcgOfflinePurchaseInStorage.getStorageStatus() == TcgOfflinePurchaseInStorageEnum.StorageStatus.IN_STORAGE.value){
                        return R.error("选择的数据已入库,不允许采购入库!");
                    }
                    if (tcgOfflinePurchaseInStorage.getStorageStatus() == TcgOfflinePurchaseInStorageEnum.StorageStatus.CANCEL_STORAGE.value){
                        return R.error("选择的数据已取消入库,不允许采购入库!");
                    }
                }
            }

            ThrOperateCompanyApply thrOperateCompanyApply;
            BigDecimal purchaseTotalPriceAll = BigDecimal.ZERO;
            Integer source = 0;
            String remark = "";
            String sourceBid = "";
            Date date = new Date();
            //创建人
            String loginUserId = ShiroUtils.getUserId();
            TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
            for (String purchaseOrderId :listPurchaseOrderId) {
                List<TcgOfflinePurchaseInStorage> tcgOfflinePurchaseInStorageListNew = new TcgOfflinePurchaseInStorage()
                        .addLeftJoin("TCG_PurchaseByOrderSon C ON C.id = A.PurchaseOrderSonId")
                        .addLeftJoin("TCG_PurchaseByOrder AA ON C.Pid = AA.id")
                        .setStorageStatus(0)
                        .where("AA.id = '" + purchaseOrderId + "'")
                        .queryList();
                for (TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage : tcgOfflinePurchaseInStorageListNew) {
                    //赋值仓库信息
                    tcgOfflinePurchaseInStorage.setChw(params.get("chw").toString());

                    //审核信息
                    tcgOfflinePurchaseInStorage.setAuditingTime(date);
                    tcgOfflinePurchaseInStorage.setAuditingUserId(tsUserChange.getUserId());
                    tcgOfflinePurchaseInStorage.setStorageStatus(TcgOfflinePurchaseInStorageEnum.StorageStatus.IN_STORAGE.value);
                    //入库
                    //查询公司信息
                    thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(tcgOfflinePurchaseInStorage.getVgsbm()).queryFirst();

                    source = TccStockSourceEnum.Source.TCG_OfflinePurchaseInStorage.value;
                    if (tcgOfflinePurchaseInStorage.getDocumentSource() == 0) {
                        remark = "线上采购入库正常新增库存数据";
                    } else {
                        remark = "线上采购入库(组装报错)新增库存数据";
                    }
                    sourceBid = tcgOfflinePurchaseInStorage.getBid();
                    purchaseTotalPriceAll = new BigDecimal(tcgOfflinePurchaseInStorage.getSubStorageNum()).multiply(tcgOfflinePurchaseInStorage.getSubPurchasePrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //入子件库存数据
                    String companyVid = "C109";
                    R add = tccStockControlService.inWithRunning(tcgOfflinePurchaseInStorage.getBid(), tcgOfflinePurchaseInStorage.getChw(), tcgOfflinePurchaseInStorage.getSubName(),
                            tcgOfflinePurchaseInStorage.getSubStorageNum(), tcgOfflinePurchaseInStorage.getSubCode(), tcgOfflinePurchaseInStorage.getSubStorageNum(), tcgOfflinePurchaseInStorage.getSubPurchasePrice(),
                            purchaseTotalPriceAll, BigDecimal.ZERO, BigDecimal.ZERO,
                            thrOperateCompanyApply.getVgsbm(), date, 0,
                            sourceBid, source, remark, companyVid, sourceBid, tcgOfflinePurchaseInStorage.getId());
                    if (add.getCode() == 1) {
                        throw new RuntimeException(add.getMsg());
                    }

                    Long stockControlId = Long.valueOf(add.get("data").toString());
                    if (tcgOfflinePurchaseInStorage.getDocumentSource() == 0 && tcgOfflinePurchaseInStorage.getGenerateStatus() == null) {
                        //冻结库存
                        Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCG_OFFLINEPURCHASEINSTORAGE_PASS.value;
                        tccStockControlService.frozen(stockControlId, tcgOfflinePurchaseInStorage.getSubStorageNum(), sourceType, tcgOfflinePurchaseInStorage.getBid(), tcgOfflinePurchaseInStorage.getId());

                    }

                    //添加库存id
                    tcgOfflinePurchaseInStorage.setStockControlId(stockControlId);

                    //查询商品图片
                    TpProductActive tpProductActive = new TpProductActive().setCode(tcgOfflinePurchaseInStorage.getProductCode()).queryFirst();
                    tcgOfflinePurchaseInStorage.setProductImgOne(tpProductActive.getImg());
                    tcgOfflinePurchaseInStorage.setProductImgTwo(tpProductActive.getImg1());
                    tcgOfflinePurchaseInStorage.setProductImgThree(tpProductActive.getImg2());

                    //正常入库判断是否生成组装单  |组装报错不自动生成组装单
                    if (tcgOfflinePurchaseInStorage.getDocumentSource() == 0) {
                        //查询采购计划子件数据
                        TcgPurchaseByPlanSon tcgPurchasePlanSon = new TcgPurchaseByPlanSon()
                                .addLeftJoin("TCG_PurchaseByOrderSon B ON B.PurchasePlanSonId = A.id")
                                .where("B.id = " + tcgOfflinePurchaseInStorage.getPurchaseOrderSonId())
                                .queryFirst();
                        tcgPurchasePlanSon.setStoreAmount(tcgPurchasePlanSon.getStoreAmount().add(new BigDecimal(tcgOfflinePurchaseInStorage.getSubStorageNum())));
                        tcgPurchasePlanSonMapper.update(tcgPurchasePlanSon);

                        //判断是否完整
                        TcgPurchasePlanGoods tcgPurchasePlanGoods = new TcgPurchasePlanGoods()
                                .where("(SELECT count(*) FROM TCG_PurchaseByPlanSon B WHERE B.pid = ' " + tcgPurchasePlanSon.getPid() + "' AND B.SubTotalAmount != B.StoreAmount) = 0")
                                .setId(tcgPurchasePlanSon.getPid())
                                .queryFirst();
                        if (tcgPurchasePlanGoods != null) {
                            //回填采购计划母件完整性
                            tcgPurchasePlanGoods.setStoreIntegrity(1);
                            tcgPurchasePlanGoodsMapper.update(tcgPurchasePlanGoods);

                            if (tcgOfflinePurchaseInStorage.getGenerateStatus() == null) {
                                //生成组装单
                                String bid = commonApiServiceAssemble.getCommonNextBid(MENUID1);
                                TccOfflineAssemble tccOfflineAssemble = new TccOfflineAssemble();
                                tccOfflineAssemble.setBid(bid);
                                tccOfflineAssemble.setState(TccOfflineAssembleEnum.State.NOT.value);
                                tccOfflineAssemble.setPrintStatus(TccOfflineAssembleEnum.PrintStatus.NOT_PRINT.value);
                                tccOfflineAssemble.setParentPreAssembleNumber(tcgPurchasePlanGoods.getSpAmount());
                                tccOfflineAssemble.setParentAssembleNumber(0);
                                tccOfflineAssemble.setStatus(1);
                                tccOfflineAssembleMapper.insert(tccOfflineAssemble);

                                //查询该母件下的所有子件
                                List<TcgOfflinePurchaseInStorage> tcgOfflinePurchaseInStorageList = new TcgOfflinePurchaseInStorage().
                                        setPurchaseOrderGoodsId(tcgPurchasePlanGoods.getId())
                                        .where("A.id != " + tcgOfflinePurchaseInStorage.getId() + " AND A.storageStatus != 1").queryList();
                                tcgOfflinePurchaseInStorageList.add(tcgOfflinePurchaseInStorage);

                                tcgOfflinePurchaseInStorage.setAssembledStatus(TcgOfflinePurchaseInStorageEnum.AssembledStatus.IN_ASSEMBLY.value);
                                for (TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage1 : tcgOfflinePurchaseInStorageList) {
                                    TccOfflineAssembleItem tccOfflineAssembleItem = new TccOfflineAssembleItem();
                                    tccOfflineAssembleItem.setPbid(bid);
                                    tccOfflineAssembleItem.setOfflinePurchaseStorageId(tcgOfflinePurchaseInStorage1.getId());
                                    tccOfflineAssembleItem.setStockControlId(tcgOfflinePurchaseInStorage1.getStockControlId());
                                    tccOfflineAssembleItem.setSubPlanStorageNum(tcgOfflinePurchaseInStorage1.getSubStorageNum());
                                    tccOfflineAssembleItem.setSubRealStorageNum(0);
                                    tccOfflineAssembleItem.setSubAssembleLeftNum(tcgOfflinePurchaseInStorage1.getSubStorageNum());
                                    tccOfflineAssembleItem.setStatus(1);
                                    tccOfflineAssembleItemMapper.insert(tccOfflineAssembleItem);

                                    tcgOfflinePurchaseInStorage1.setAssembledStatus(TcgOfflinePurchaseInStorageEnum.AssembledStatus.IN_ASSEMBLY.value);

                                    tpProductActive = new TpProductActive().setCode(tcgOfflinePurchaseInStorage1.getProductCode()).queryFirst();

                                    tcgOfflinePurchaseInStorage1.setProductImgOne(tpProductActive.getImg());
                                    tcgOfflinePurchaseInStorage1.setProductImgTwo(tpProductActive.getImg1());
                                    tcgOfflinePurchaseInStorage1.setProductImgThree(tpProductActive.getImg2());
                                    tcgOfflinePurchaseInStorageMapper.update(tcgOfflinePurchaseInStorage1);
                                }
                            }
                        }
                    }
                    tcgOfflinePurchaseInStorageMapper.update(tcgOfflinePurchaseInStorage);
                }
            }
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return R.ok();
    }

    //批量导入
    @Override
    @Transactional
    public R importInfo(String rows,Long menuId) throws Exception{
        logger.info("导入的数据：\n" + rows);

        JSONArray detailList = JSON.parseArray(rows);
        String errorMsg = "";
        HashSet<String> aliLogisticsBillNoList = new HashSet<>();
        String bid = null;
        for(int i=0;i<detailList.size();i++) {
            JSONObject info = detailList.getJSONObject(i);
            Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
            if(i==0 && infoMap.get("errorMsg")!=null){
                errorMsg = infoMap.get("errorMsg").toString();
            }
            if(i==0 && infoMap.get("bid")!=null){
                bid = infoMap.get("bid").toString();
            }
            //验证：运单号
            if (checkUtil.isNullByObject(infoMap.get("aliLogisticsBillNo"))) {
                return R.error("物流运单号不允许为空");
            }
            aliLogisticsBillNoList.add(infoMap.get("aliLogisticsBillNo").toString());
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (String aliLogisticsBillNo : aliLogisticsBillNoList){
            List<TcgOfflinePurchaseInStorage> tcgOfflinePurchaseInStorageList = new TcgOfflinePurchaseInStorage().setAliLogisticsBillNo(aliLogisticsBillNo).queryList();
            if (tcgOfflinePurchaseInStorageList.size() == 0){
                if (bid == null || bid.equals("")){
                    bid = commonApiService.getCommonNextBid(MenuId.TCG_OfflinePurchaseInStorageBc);
                    //新增错误数据
                }
                stringBuffer.append(aliLogisticsBillNo);
                stringBuffer.append(",");
            }else {
                for (TcgOfflinePurchaseInStorage tcgOfflinePurchaseInStorage : tcgOfflinePurchaseInStorageList){
                    if (tcgOfflinePurchaseInStorage.getPrintStatus() != TcgOfflinePurchaseInStorageEnum.PrintStatus.SIGN_NOT_PRINT.value){
                        tcgOfflinePurchaseInStorage.setPrintStatus(TcgOfflinePurchaseInStorageEnum.PrintStatus.SIGN_NOT_PRINT.value);
                        tcgOfflinePurchaseInStorageMapper.update(tcgOfflinePurchaseInStorage);
                    }
                }
            }
        }
        return R.ok(errorMsg+stringBuffer,bid);
    }
}
